<template>
  <div>
    <EditorVue
        :content="content"
        :readOnlys="readOnlys"
        @changeData="hChangeData"
        @uploadImg="hUploadImg"
    />
    <el-divider></el-divider>

    <!-- 文档信息编辑 -->
    <div>
      <!--        <el-dialog title="文档信息" :visible.sync="dialogFormVisible1">-->
      <div class="form">
        <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm" :rules="formRule">
          <el-form-item label="文档分类" prop="categoryId">
            <el-select v-model="ruleForm.categoryId" placeholder="请选择文档类别">
              <el-option v-for="option in categorys" :key="option.id" :label="option.categoryName" :value="option.id" style="float: left"></el-option>
            </el-select>
          </el-form-item>

          <!--            <el-form-item label="是否为通知" prop="notice" style="text-align:left;float:left;padding-right: 60px;margin-left: 10px">-->
          <!--                <el-checkbox label="" name="notice" v-model="ruleForm.notice"></el-checkbox>-->
          <!--            </el-form-item>-->


          <el-form-item label="文档标题" prop="title">
            <el-input v-model="ruleForm.title" style="width: 220px;float: left"></el-input>
          </el-form-item>
<!--          <el-form-item label="标签" prop="tags">-->
<!--            <el-tag type="success" v-for="option in categorys" :key="option.id" :label="option.name" :value="option.id" closable>{{option.name}} </el-tag>-->
<!--          </el-form-item>-->

          <el-form-item label="标签" prop="selectedTags">
            <el-select v-model="selectedTags" multiple placeholder="请选择标签">
              <el-option
                  v-for="tag in tags"
                  :key="tag.id"
                  :label="tag.tagname"
                  :value="tag.tagname"
              >
                <el-tag>{{ tag.tagname }}</el-tag>
              </el-option>
            </el-select>
          </el-form-item>



<!--          <el-form-item label="作者" prop="nAuthor">-->
<!--            <el-input v-model="ruleForm.nAuthor" style="width: 220px;float: left"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="预览图上传">
            <el-upload
                class="avatar-uploader"
                name="file"
                action="http://124.70.54.24:3001/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
<!--          submitForm-->
          <el-form-item style="padding:0px 80px 10px 0px;">
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>

        </el-form>
      </div>
      <!--      </el-dialog>-->
    </div>

    <!--    <div>-->
    <!--      &lt;!&ndash; 选择本地文件弹窗 &ndash;&gt;-->
    <!--      <el-dialog title="选择本地文档" :visible.sync="dialogFormVisible2">-->
    <!--        <el-upload-->
    <!--          class="upload-demo"-->
    <!--          ref="upload"-->
    <!--          action="https://jsonplaceholder.typicode.com/posts/"-->
    <!--          accept=".xlsx,.xls"-->
    <!--          :limit="1"-->
    <!--          :on-preview="handlePreview"-->
    <!--          :on-remove="handleRemove"-->
    <!--          :file-list="fileList"-->
    <!--          :auto-upload="false">-->
    <!--          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
    <!--          <el-button  style="margin-left: 10px;" size="small" type="success" plain @click="dialogFormVisible = true">编辑文档信息</el-button>-->
    <!--          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
    <!--          <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过500kb</div>-->
    <!--        </el-upload>-->
    <!--      <ChooseLocalFile/>-->


    <!--      </el-dialog>-->
    <!--    </div>-->

  </div>
</template>

<script>
import EditorVue from '../components/editorVue.vue'
// import ChooseLocalFile from "@/components/ChooseLocalFile";
export default {
  name: "UpdateNewsComponent",
  components: {
    EditorVue,
    // ChooseLocalFile
  },
  //从父组件传过来的数据，为回显的数据
  props: {
    from: {
      type: String,
      default: ''
    },
    oldRuleForm: {
      type: String, //数据类型有 String、Number、Boolean、Array ...
      default: ''// 默认值
    },
    dialogFormVisible0: {
      type: Boolean,
      default: true
    }

  },
  data() {
    // this.ruleForm=JSON.parse(this.formData);
    return {
      newTag: "", // 新增标签名称
      imageUrl:"",
      categorys:[],
      tags: [], // 存储标签列表
      selectedTags: [], // 存储选中的标签
      isdeleteImg:false,
      // url: VUE_APP_URL.BASE_URL+ '/file/img/',
      isNews: false,
      params:new FormData(),
      readOnlys: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      content: '',
      ruleForm: {
        nPic:''
      },
      rules: {
        nName: [
          {required: true, message: '请输入文档名称', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        nAuthor: [
          {required: true, message: '请输入作者名称', trigger: 'blur'},
          {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
        ],
      },
      formRule: {
        title: [
          {required: true, message: '请输入标题名称', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        categoryId:[
          {required: true, message: '请选择类别', trigger: 'blur'},
        ],
        // ifSelectedTags: { required: true, message: '请选择标签', trigger: 'blur' },
        selectedTags:[
          {validator: (rule, value, callback) => {
              if (this.selectedTags.length>0) {
                callback();
              } else {
                callback(new Error('请选择标签'));
              }
            }, trigger: 'blur'}
        ]
      },
      fileList: []
    };
  },
  methods: {
    getTags(){
      this.$axios.get("http://localhost:8081/tag/findall")
          .then(response => {
            console.log("response")
            console.log(response)
            this.tags = response.data;
          })
          .catch(error => {
            this.$message.error("获取标签失败，请联系管理员")
          });
    },
    publishBlog() {
      // 获取选中的标签
      console.log(this.selectedTags.length);
      // 执行发布博客的逻辑
      // ...
    },
    addTag() {
      if (this.newTag) {
        this.tags.push(this.newTag); // 将新增标签添加到标签列表
        this.newTag = ""; // 清空新增标签名称
      }
    },
    removeTag(index) {
      this.tags.splice(index, 1); // 删除指定位置的标签
      console.log("tags")
      console.log(this.tags);
    },
    uploadFileAndParams(param) {
      this.params.append("pic", param.file)
    },
    handleRemove(file, fileList) {
      this.params.remove('file');
    },
    hChangeData(editDataHtml) {
      // 获取最新的html数据
      this.content = editDataHtml
    },
    hUploadImg(file, insertFn) {
      // 插入图片，调接口返回图片url,通过插入conteng
      var params=new FormData();
      params.append("file",file)
     this.$axios({
        url:'/file/uploadFile2',
        method: 'POST',
        // transformRequest: [function(data, headers) {
        //   // 去除post请求默认的Content-Type
        //   delete headers.post['Content-Type']
        //   return data
        // }],
        data: params
      }).then((res) => {

        var jason = eval("(" + res.data + ")");
        insertFn(jason.data.url)
      })
      // let imgUrl = 'https://img1.baidu.com/it/u=608404415,1639465523&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800'
      // insertFn(imgUrl);


      // 设置只读
      // this.readOnlys = true;
    },
    //限定添加新闻图片的图片大小
    handleAvatarSuccess(res){
      console.log('上传请求返回的数据',res)
      if(res.code==200){
        //成功
        this.imageUrl = res.data;
        //赋给修改用户
        this.ruleForm.path = res.data;
      }
    },
    beforeAvatarUpload(file){
      console.log('上传之前',file);
      //判断大小和类型是否符合条件,最多5m的大小限制，并且只能是png、jpg、jpeg、gif、webp等格式
      //使用正则表达式来判断数据是否符合指定条件
      if(!/(png|jpg|jpeg|gif|webp)$/.test(file.type)){
        this.$message({
          message:"只能上传png、jpg、jpeg、gif、webp格式的图片",
          type:"error"
        })
        return false;
      }
      if(file.size > 1024 *1024 *2){
        this.$message({
          message:"只能上传大小小于2mb的图片",
          type:"error"
        })
        return false;
      }
      return true;//允许上传
    },
    submitForm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let config = {
            headers: {
              'Content-Type': 'application/json'
            }
          };
          let requestBody = {
            id: this.ruleForm.id,
            title: this.ruleForm.title,
            updateTime:this.ruleForm.updateTime,
            categoryId: this.ruleForm.categoryId,
            path: this.ruleForm.path,
            view: this.ruleForm.view,
            tags: JSON.stringify(this.selectedTags),
            content: this.content,
          };
          // console.log("requestBody")
          // console.log(requestBody)
          this.$axios.post("/tbBlog/edit/", JSON.stringify(requestBody), config)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success("修改成功!");
                } else if (res.data.code === 401) {
                  this.$message.error("无权限！");
                } else {
                  this.$message.error("修改失败");
                }
              })
              .finally(() => {
                this.shutdown();
              });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // submitForm() {
    //   this.$refs["ruleForm"].validate((valid) => {
    //     let config = {
    //       headers: {
    //         'Content-Type': 'application/json'
    //       }
    //     };
    //     let params = new FormData();
    //     if (valid) {
    //
    //       params.append("id", this.ruleForm.id)
    //       params.append("title", this.ruleForm.title)
    //       params.append("content", this.content)
    //       params.append("categoryId", this.ruleForm.categoryId)
    //       params.append("path", this.ruleForm.path)
    //       params.append("view", this.ruleForm.view)
    //       params.append("tags", JSON.stringify(this.tags))
    //       this.$axios.post("/tbBlog/edit/", this.params,config).then(
    //           (res) => {
    //             if (res.data.code === 200) {
    //               this.$message.success("修改成功!");
    //             } else if (res.data.code === 401) {
    //               this.$message.error("无权限！");
    //             } else {
    //               this.$message.error("修改失败")
    //             }
    //
    //           }
    //       ).finally(() => {
    //         this.shutdown();
    //       })
    //     } else {
    //       console.log('error submit!!');
    //       return false;
    //     }
    //   });
    // },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleChange(event) {
      console.log(event)
      // document.getElementById("img").style.display="block";
    },
    // 文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    handlePreview(file) {
      console.log(file);
    },
    Img(param) {
      this.file = param.file;
    },
    uploadImg() {
      let fd = new FormData();
      fd.append('pic', this.file);
      fd.append('n_title', this.ruleForm.nTitle)
      fd.append('n_author', this.ruleForm.nAuthor)
      fd.append('n_class', this.ruleForm.nClass)
      fd.append('n_content', this.content)
      this.$axios.post('/news/addNews', fd).then((res) => {
        if (res.data.code === 200) {
          this.shutdown();
          this.$message.success("上传成功！")
        } else if (res.data.code === 401) {
          this.$message.error("无权限！");
        } else {
          this.$message.error('上传失败！')
        }
      }).finally(() => {
        this.shutdown();
      })
    },
    shutdown: function () {
      this.$emit('update:shutdown', false)
    },
    getCategorys(){
      this.$axios.get("http://localhost:8081/Category/findall")
          .then(response => {
            console.log("response")
            console.log(response)
            this.categorys = response.data;
          })
          .catch(error => {
            this.$message.error("获取分类失败，请联系管理员")
          });
    },
  },
  mounted() {
    this.ruleForm = JSON.parse(this.oldRuleForm);
    this.imageUrl=this.ruleForm.path;
    // let param = 'id=' + this.ruleForm.id
    // this.$axios.get('/tbBlog/edit?' + param).then((res) => {
    //   if (res.data.code === 200) {
    //     // this.isNews = true
    //     // res.data.data.
    //     let api = this.url;
    //     this.url = api + res.data.data
    //   } else if (res.data.code === 401) {
    //     this.$message.error("无权限！");
    //   }
    // })
    this.content = this.ruleForm.content;
    this.selectedTags = JSON.parse(this.ruleForm.tags);
    this.getCategorys();
    console.log("rulform")
    console.log(this.ruleForm)
    //从数据库获取标签集合！！！
    this.getTags();
  }
};
</script>
<style scoped>
.form {
  width: 400px;
  margin: 0 auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.img {
  padding-bottom: 10px;
}
</style>
